Home:ALL Converter>DJANGO - Using simple history, how can I show both a base model record and a related history group calculation in one query?

DJANGO - Using simple history, how can I show both a base model record and a related history group calculation in one query?

Ask Time:2018-08-03T02:16:33         Author:Rosey

Json Formatter

I am using the simple history library for my Django project. It's pretty nifty, but I'm having trouble showing aggregated history stats next to a base model object. Here's what my model looks like:

from django.db import models
from django.contrib.auth.models import User
from simple_history.models import HistoricalRecords

class RepairForm(models.Model):
    user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING,)
    return_number = models.CharField(max_length=200, unique=True)
    status_id = models.ForeignKey(RFormStatus, on_delete=models.DO_NOTHING)
    ...

    history = HistoricalRecords()

    def __str__(self):
        return self.return_number

The Docs lead me to believe the proper way of accessing historical records is using the history manager. I can get both sets of information I want:

All Forms (base model objects) -

RepairForm.objects.all()

User ID |             Return Number            | Status ID
-----------------------------------------------------------
33      | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001
44      | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002
...

A history calculation (history object) In this example I am getting the latest event of each form -

RepairForm.history.all()\
            .values('return_number').annotate(latest_event_date=Max('history_date'))\
            .order_by('return_number')

          Return Number              | latest_event_date
-----------------------------------------------------------
0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 7/27/2018
5f699795-5119-4dcd-8b94-34f7056e732c | 8/1/2018
...

I feel like this should be possible to do in one query though no? One query that outputs something like this:

User ID |             Return Number            | Status ID | latest_event_date
------------------------------------------------------------------------------
33      | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001     | 7/27/2018
44      | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002     | 8/1/2018
...

Author:Rosey,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51659928/django-using-simple-history-how-can-i-show-both-a-base-model-record-and-a-rel
yy